﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ObjectTransposeApi.Structure;
using ObjectTransposeApi.Helper;

namespace ObjectTransposeApi.Handler.Property
{
    /// <summary/>
    internal class MatchToNullablePropertyHandler : AbstractPropertyHandler
    {
        /// <summary/>
        internal override IEnumerable<QueueStructure> Process(PropertyStructure propertyStructure)
        {
            // read the source property value
            object sourceValue = propertyStructure.SourcePropertyInfo.GetValue(propertyStructure.Source, null);

            // if the value is not set then exit ... this is the last item in the chain
            if (sourceValue == null)
            {
                return base._successor.Process(propertyStructure);
            }

            Type nullableDestinationType = NullableHelper.FetchNullableType(propertyStructure.DestinationPropertyInfo.PropertyType);

            // if not nullable then exit
            if (nullableDestinationType == null)
            {
                return base._successor.Process(propertyStructure);
            }

            // if the types are not the same then nothing to do
            if (nullableDestinationType != propertyStructure.SourcePropertyInfo.PropertyType)
            {
                return base._successor.Process(propertyStructure);
            }

            // set the destination value
            propertyStructure.DestinationPropertyInfo.SetValue(propertyStructure.Destination, sourceValue, null);

            // nothing to return
            return null;
        }
    }
}
